<?php

namespace app\admin\jobs;

use app\admin\model\MarketSmCopywriting as MarketSMCopywritingModel;
use app\common\RabbitMQClient;
use app\admin\service\CryptoNews as CryptoNewsService;

class MarketSMCopywritingGeneration
{
    /**
     * 发布社媒文案到社媒平台 具体实现
     * @param $data
     * @return bool
     */
    public function execute()
    {

        $callback = function ($msg) {
            $data = $msg;

            if ($data) {
                $data = json_decode($data, true);

                $oMarketSmCopywritingModel = MarketSmCopywritingModel::with('task')->where([
                    ['task_status', '=', 0],
                    ['redo_num', '<', 5],
                    ['id', '=', $data['id']]
                ])->find();
                if(!$oMarketSmCopywritingModel){
                    return false;
                }

                $param = [
                    'id' => $oMarketSmCopywritingModel->task ? $oMarketSmCopywritingModel->task->crypto_news_id : '',
                    'platform' => $oMarketSmCopywritingModel->task ? $oMarketSmCopywritingModel->task->channel_id : '',
                    'cue_word' => $oMarketSmCopywritingModel->task ? $oMarketSmCopywritingModel->task->cue_word : '',
                    'language' => $oMarketSmCopywritingModel->task ? $oMarketSmCopywritingModel->task->language_id : '',
                    'associatedMiners' => $oMarketSmCopywritingModel->task ? $oMarketSmCopywritingModel->task->mining_machine : '{}',
                    'writing_id' => $oMarketSmCopywritingModel->id
                ];
                $oCryptoNewsService = new CryptoNewsService();

                $res = $oCryptoNewsService->publishByQueue($param);
                return $res['code'] != 0 ? false : true;
            }
            return true;
        };

        // 确保 durable 参数为 true，以保证消息持久化
        $rabbitMQService = new RabbitMQClient();
        $rabbitMQService->receiveMessage('createCopywriting',$callback);
        $rabbitMQService->close();
    }
}
